package com.nbpt;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.nbpt.db.AccountDBHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private TextView tvUsername, tvPassword;
    private EditText etUsername, etPassword;
    private Button bt_login, bt_clear;
    CheckBox checkBox;
    SharedPreferences sp;
//    String errMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etUsername = findViewById(R.id.et_username);
//        etUsername.setText("test");
        etPassword = findViewById(R.id.et_password);
        checkBox=findViewById(R.id.check);

        sp=getSharedPreferences("MainActivity",Context.MODE_PRIVATE);

        String username=sp.getString("account","");//第二个为读取无时 指定默认值
        String password=sp.getString("password","");
        boolean check=sp.getBoolean("check",false);

        etUsername.setText(username);
        etPassword.setText(password);
        checkBox.setChecked(check);
    }

    public void clearAll(View view) {
        etUsername.setText("");
        etPassword.setText("");
        etPassword.clearAnimation();
        Toast.makeText(this, "已经清除!", Toast.LENGTH_SHORT).show();
    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                Toast.makeText(MainActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
            }else {
                String errMessage= (String) msg.obj;
                Toast.makeText(MainActivity.this, errMessage, Toast.LENGTH_SHORT).show();
            }
        }
    };

    JSONObject jsonAccount=new JSONObject();
    public void login(View view){

        String username = etUsername.getText().toString();
        String password = etPassword.getText().toString();
        try {
            jsonAccount.put("username",username);
            jsonAccount.put("password",password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection connection=null;
            try {
                URL url=new URL("http://192.168.1.7:9020/iot/user/login");
                connection=(HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(50000);
                connection.setRequestProperty("connection","Keep_Alive");
                connection.setRequestProperty("Charset","UTF-8");
                connection.setRequestProperty("Content-Type","application/json");
                OutputStream os=connection.getOutputStream();
                os.write(jsonAccount.toString().getBytes());
                os.flush();
                os.close();
                if(connection.getResponseCode()==200){
                    InputStream is=connection.getInputStream();
                    BufferedReader reader=new BufferedReader(new InputStreamReader(is));
                    String line;
                    String response="";
                    while ((line=reader.readLine())!=null){
                        response+=line;
                    }
                    Log.e("MainActivity",response);
                    JSONObject jsonResponse=new JSONObject(response);
                    int code=jsonResponse.getInt("code");
                    String data=jsonResponse.getString("data");
                    JSONObject JsonResponse=new JSONObject(data);
                    String token=JsonResponse.getString("token");
                    if (code==10001){
//                        Toast.makeText(MainActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                        handler.sendEmptyMessage(1);
                        Intent intent = new Intent(MainActivity.this, MenuActivity.class);
                        intent.putExtra("token",token);
                        startActivity(intent);
                    }else {
                        String errMessage=jsonResponse.getString("msg");
                        Message msg=new Message();
                        msg.what=0;
                        msg.obj=errMessage;
                        handler.sendMessage(msg);
//                        Toast.makeText(MainActivity.this, errMessage, Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Log.e("MainActivity","服务器返回错误！");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

//    AccountDBHelper accountDBHelper = new AccountDBHelper(MainActivity.this);
////    Cursor cursor = accountDBHelper.searchAccount();
////        if(cursor.getCount()>0)
////        {
////        int i = 0;
////        boolean flag=false;
////        cursor.moveToFirst();
////        while (i < cursor.getCount()) {
////            Log.e("MainActivity", "用户名" + cursor.getString(1));
////            Log.e("MainActivity", "密码" + cursor.getString(2));
////            if(username.equals(cursor.getString(1)))
////            {
////                flag=true;
////                if(password.equals(cursor.getString(2)))
////                {
////                    Toast.makeText(this, "登录成功！", Toast.LENGTH_SHORT).show();
////                    Intent intent = new Intent(MainActivity.this, MenuActivity.class);
////                    startActivity(intent);
////                    if(checkBox.isChecked()){//勾选上状态
////                        //保存当前输入用户名密码
////                        SharedPreferences.Editor editor=sp.edit();
////                        editor.putString("account",username);
////                        editor.putString("password",password);
////                        editor.putBoolean("check",true);
////                        editor.commit();
////                    }else {
////                        SharedPreferences.Editor editor=sp.edit();
////                        editor.putBoolean("check",false);
////                        editor.commit();
////                        editor.clear();
////                    }
////                }
////                else
////                {
////                    Toast.makeText(this, "密码错误，请重新输入！", Toast.LENGTH_SHORT).show();
////                }
////                break;
////            }
////            cursor.moveToNext();
////            i++;
////        }
////        cursor.close();
////        if(!flag)
////        {
////            Toast.makeText(this, "没有账号，请先注册！", Toast.LENGTH_SHORT).show();
////        }
////        }
////        else{
////        Toast.makeText(this, "没有账号，请先注册！", Toast.LENGTH_SHORT).show();
////        Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
//////        startActivity(intent);
////        startActivityForResult(intent,0);
////    }
}

        public void register (View view){
            Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
            //startActivity(intent);
            startActivityForResult(intent,0);
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0){
            if (resultCode==1) {
                String username=data.getStringExtra("extra1");
                etUsername.setText(username);
                String password=data.getStringExtra("extra2");
                etPassword.setText(password);
            }
            }
        }
    }

